﻿/*              Copyright(c) 2008 Dave Sexton              *
 * http://www.codeplex.com/DocProject                      *
 * http://www.codeplex.com/DocProject/Project/License.aspx *
 ***********************************************************/
using System;
using System.Collections.Generic;
using System.Text;

namespace DaveSexton.DocToMaml
{
	internal sealed class FileGuidManager
	{
		#region Public Properties
		#endregion

		#region Private / Protected
		private Dictionary<string, Guid> fileGuids = new Dictionary<string, Guid>(StringComparer.OrdinalIgnoreCase);
		#endregion

		#region Constructors
		/// <summary>
		/// Constructs a new instance of the <see cref="FileGuidManager" /> class.
		/// </summary>
		public FileGuidManager()
		{
		}
		#endregion

		#region Methods
		private static string GetKey(string file)
		{
			return System.IO.Path.GetFileName(file);
		}

		[System.Diagnostics.DebuggerHidden]
		private static Guid CreateGuidForFile(string file)
		{
			string name = System.IO.Path.GetFileNameWithoutExtension(file);

			try
			{
				return new Guid(name);
			}
			catch (FormatException) { }

			using (System.Security.Cryptography.MD5 md5 = System.Security.Cryptography.MD5.Create())
			{
				return new Guid(md5.ComputeHash(Encoding.Unicode.GetBytes(file)));
			}
		}

		public void Clear()
		{
			fileGuids.Clear();
		}

		public void RemoveGuid(string file)
		{
			fileGuids.Remove(GetKey(file));
		}

		public void SetGuid(string file, Guid guid)
		{
			fileGuids[GetKey(file)] = guid;
		}

		public void EnsureGuids(IEnumerable<IInput> inputs)
		{
			foreach (IInput input in inputs)
			{
				foreach (string file in input.Files)
				{
					string key = GetKey(file);

					if (!fileGuids.ContainsKey(key))
						fileGuids.Add(key, CreateGuidForFile(key));
				}
			}
		}

		public Guid GetGuid(string file)
		{
			string key = GetKey(file);

			if (fileGuids.ContainsKey(key))
				return fileGuids[key];
			else
				return Guid.Empty;
		}

		public Guid GetOrCreateGuid(string file)
		{
			string key = GetKey(file);

			if (fileGuids.ContainsKey(key))
				return fileGuids[key];
			else
			{
				Guid guid = CreateGuidForFile(key);
				fileGuids.Add(key, guid);
				return guid;
			}
		}
		#endregion
	}
}
